const fs = require('fs-extra');
const util = require('util')

// 我为数不多定义的异步函数
async function readFile(path) {
    try {
        // 读取文件状态
        const stats = await util.promisify(fs.stat)(path)
        if (!stats.isFile()) throw new Error(`路径 \x1b[47m${path}\x1b[0m 不是文件！！！`)
    } catch (err) {
        console.error('\x1B[31m文件不存在！！！\x1B[0m\n\x1B[36m请确保第三个参数已正确传入\x1B[0m\n\x1b[42m------------\x1b[0m\n', err);
        return
    }

    return new Promise((resolve, rejects) => {
        fs.readFile(path, "utf-8", (err, data) => {
            err ? rejects(err) : resolve(data)
        })
    })
}

function writeFile(path, content) {
    return new Promise(resolve => {
        fs.createFile(path, err => {
            if (err) throw err
            fs.writeFile(path, content, err => {
                if (err) throw err;
                resolve()
            })
        })
    })
}

module.exports = {
    readFile,
    writeFile
}